<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/8
 * Time: 8:35
 */

namespace Api\Controller;


class FreestockController extends BeforController
{
    /**
     * 获取用户的自选股票代码
     */
    private function getOptional()
    {
        $dboptional = M('Optional');
        $codes      = $dboptional->field('code')->where('uid=' . $this->_userinfo['muid'])->select();
        if (empty($codes)) {
            return false;
        }

        return $codes;
    }

    /**
     * 我关注的股票
     */
    public function optional()
    {
        $mycodes = self::getOptional();
        if (empty($mycodes)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选股票'], 'json');
        }
        foreach ($mycodes as $k => $code) {
            $mycodes[$k] = $code['code'];
        }
        $db   = M('Stock');
        $data = $db->field(['name', 'pinyin', 'code', 'type'])->where(['code' => ['in', $mycodes]])->select();
        foreach ($data as $k => $v) {
            $v['ssid'] = $v['code'];
            unset($v['code']);
            $data[$k] = $v;
        }
        $this->response(['code' => 0, 'data' => ['list' => $data]], 'json');
    }

    /**
     * 自选研报
     * 从接口中获取 无法得知具体条数
     */
    public function reports()
    {
        $pageCount = I('pageCount', 1);
        $showCount = I('showCount', 20);
        // 获取当前用户选择的股票
        $mycodes = self::getOptional();
        if (empty($mycodes)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选股票'], 'json');
        }
        foreach ($mycodes as $k => $code) {
            $mycodes[$k] = $code['code'];
        }
        $url = 'http://122.144.130.107:8094/cgi-bin/GetReportData.ashx?where=(zqdm in (\'' . implode('\',\'',
                $mycodes) . '\'))&page=' . $pageCount . '&size=' . $showCount;
        try {
            $req = \Requests::get($url);
        } catch (\Requests_Exception $e) {
            $this->response(['code' => __LINE__, 'msg' => '服务出走了,鹳狸猿泪奔'], 'json');
        }
        $dbstock  = M('Stock');
        $codename = $dbstock->field('name,code')->where(['code' => ['in', $mycodes]])->select();
        foreach ($codename as $k => $v) {
            unset($codename[$k]);
            $codename[$v['code']] = $v['name'];
        }
        $data = str_replace(['var data=["', '"]'], '', $req->body);
        $data = explode('","', $data);
        foreach ($data as $val) {
            $val     = explode(',', $val);
            $lists[] = [
                'author'    => $val[5],
                'stockCode' => $val[2],
                'stockName' => $codename[$val[2]],
                'text'      => $val[4],
                'time'      => $val[7],
                'title'     => $val[4],
                'url'       => U('Home/News/reports', ['id' => $val[0]], 'html', true)
            ];
        }
        $this->response(['code' => 0, 'data' => ['list' => $lists, 'totalCount' => $showCount]], 'json');
    }

    /**
     * 自选指数
     */
    public function exponential()
    {
        $mycodes = self::getOptional();
        if (empty($mycodes)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选指数'], 'json');
        }
        // 判断是否是指数
        foreach ($mycodes as $key => $code) {
            $mycodes[$key] = $code['code'];
        }
        $dbstock  = M('Stock');
        $codedata = $dbstock->field('name,code')->where([
            'type' => ['in', [0, 3, 10, 12, 31]],
            'code' => ['in', $mycodes]
        ])->select();
        if (empty($codedata)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选指数'], 'json');
        }
        foreach ($codedata as $key => $code) {
            unset($codedata[$key]);
            $codedata[$code['code']] = $code['name'];
        }
        // 自选指数
        import('Common.Util.Stock');
        $stock = new \Stock();
        $quote = $stock->GetQuote(array_keys($codedata));
        foreach ($quote as $key => $value) {
            $list[] = [
                'code'      => $key,
                'last'      => $value[3],
                'name'      => $value[0],
                'risePrice' => ($value[3] - $value[1]),
                'riseRate'  => ''
            ];
        }
        $this->response(['code' => 0, 'data' => ['list' => $list]], 'json');
    }

    /**
     * 自选资金
     * name        string
     * netInflows    净流入    number
     * stockCode        string
     * tenMasukura    十日增仓    number
     * tenRankings    十日排名    number
     * threeMasukura    3日增仓    number
     * threeRankings    3日排名    number
     * todaMasukura    今日增仓    number
     * todayRankings
     */
    public function capital()
    {
        $mycodes = self::getOptional();
        if (empty($mycodes)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选股票'], 'json');
        }
        // 判断是否是指数
        foreach ($mycodes as $key => $code) {
            $mycodes[$key] = $code['code'];
        }
        $dbstock  = M('Stock');
        $codename = $dbstock->field('name,code')->where(['code' => ['in', $mycodes]])->select();
        foreach ($codename as $k => $v) {
            unset($codename[$k]);
            $codename[$v['code']] = $v['name'];
        }
        foreach ($codename as $k => $val) {
            $url = 'http://122.144.130.107:8094/cgi-bin/GetZjlxData.ashx?RequestType=3&StockCode=' . $k . '&DataType=ZJLX';
            try {
                $req = \Requests::get($url);
            } catch (\Requests_Exception $e) {
                $this->response(['code' => __LINE__, 'msg' => '服务出走了,鹳狸猿泪奔'], 'json');
            }
            $data   = str_replace(['{', '}'], '', $req->body);
            $data   = explode(',', $data);
            $list[] = [
                'netInflows'    => str_replace('ZlIn:', '', $data[1]),
                'stockCode'     => $k,
                'name'          => $val,
                'tenMasukura'   => '',
                'tenRankings'   => '',
                'threeMasukura' => '',
                'threeRankings' => '',
                'todaMasukura'  => '',
                'todayRankings' => ''
            ];
        }
        $this->response(['code' => 0, 'data' => ['list' => $list, 'totalCount' => count($list)]], 'json');
    }

    /**
     * 自选行情
     */
    public function stock()
    {
        $mycodes = self::getOptional();
        if (empty($mycodes)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选股票'], 'json');
        }
        // 判断是否是指数
        foreach ($mycodes as $key => $code) {
            $mycodes[$key] = $code['code'];
        }
        $dbstock  = M('Stock');
        $codedata = $dbstock->field('name,code,type')->where(['code' => ['in', $mycodes]])->select();
        if (empty($codedata)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选指数'], 'json');
        }
        foreach ($codedata as $key => $code) {
            unset($codedata[$key]);
            if (in_array($code['type'], [0, 1, 2])) {
                $now_code            = 'sh' . $code['code'];
                $codedata[$now_code] = $code['name'];
            } elseif (in_array($code['type'], [3, 4, 5,16,15])) {
                $now_code            = 'sz' . $code['code'];
                $codedata[$now_code] = $code['name'];
            }
        }
        // 自选指数
        import('Common.Util.Stock');
        $stock = new \Stock();
        $quote = $stock->GetQuote(array_keys($codedata));
        foreach ($quote as $key => $value) {
            $list[] = [
                'code'      => $key,
                'last'      => $value[3],
                'name'      => $value[0],
                'risePrice' => round(($value[3] - $value[1]), 2),
                'riseRate'  => round(($value[3] - $value[1]) / $value[1], 4)
            ];
        }
        $this->response(['code' => 0, 'data' => ['list' => $list]], 'json');
    }

    /**
     * 自选股新闻
     */
    public function news()
    {
        $pageCount = I('pageCount', 1);
        $showCount = I('showCount', 20);
        // 获取当前用户选择的股票
        $mycodes = self::getOptional();
        if (empty($mycodes)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无自选股票'], 'json');
        }
        foreach ($mycodes as $k => $code) {
            $mycodes[$k] = $code['code'];
        }
        $url = 'http://122.144.130.107:8094/cgi-bin/GetStockNews.ashx?where=(zqdm in (\'' . implode('\',\'',
                $mycodes) . '\'))&page=' . $pageCount . '&size=' . $showCount;
        try {
            $req = \Requests::get($url);
        } catch (\Requests_Exception $e) {
            $this->response(['code' => __LINE__, 'msg' => '服务出走了,鹳狸猿泪奔'], 'json');
        }
        $dbstock  = M('Stock');
        $codename = $dbstock->field('name,code')->where(['code' => ['in', $mycodes]])->select();
        foreach ($codename as $k => $v) {
            unset($codename[$k]);
            $codename[$v['code']] = $v['name'];
        }
        $data = str_replace(['var data=["', '"]'], '', $req->body);
        $data = explode('","', $data);
        foreach ($data as $val) {
            $val     = explode(',', $val);
            $lists[] = [
                'author'    => '',
                'stockCode' => $val[1],
                'stockName' => $codename[$val[1]],
                'text'      => $val[2],
                'time'      => $val[3],
                'title'     => $val[2],
                'url'       => U('Home/News/show', ['id' => $val[0]], 'html', true)
            ];
        }
        $this->response(['code' => 0, 'data' => ['list' => $lists, 'totalCount' => $showCount]], 'json');
    }

    /**
     * 买入
     * todo:是否加入验证购买数量
     */
    public function buy()
    {
        if(parent::checktime()==false){
            $this->response(['code'=>__LINE__,'msg'=>'交易时间已经结束']);
        }
        // 同步处理 订阅关系 买入后 进入到自选队列
        $amount = I('post.amount', 0, 'int');
        $price  = I('post.price', 0);
        if (empty($amount)) {
            $this->response(['code' => __LINE__, 'msg' => '请输入购买数量'], 'json');
        }
        if (empty($price) || !is_numeric($price)) {
            $this->response(['code' => __LINE__, 'msg' => '股票价格不正确'], 'json');
        }
        $code = I('post.stockCode');
        if (empty($code)) {
            $this->response(['code' => __LINE__, 'msg' => '请输入正确的股票代码'], 'json');
        }
        $db_stock   = M('Stock');
        $stock_type = $db_stock->where(['code' => $code])->getField(['type']);
        if (in_array($stock_type, [0, 1, 2])) {
            $now_code = 'sh' . $code;
        } elseif (in_array($stock_type, [3, 4, 5,16,15])) {
            $now_code = 'sz' . $code;
        } else {
            $this->response(['code' => __LINE__, 'msg' => '请输入正确的股票代码'], 'json');
        }
        // 计算可用资金能够购买的股票数量
        $total = intval($this->_userinfo['bankroll'] / $price);
        if ($amount > $total) {
            $this->response(['code' => __LINE__, 'msg' => '你的可用资金不足以支付当前的购买数量'], 'json');
        }
        // 查询股票当前价格 买入价格高于当前价格即可成交
        import('Common.Util.Stock');
        $stock = new \Stock();
        $data  = $stock->GetQuote($now_code);
        if (empty($data)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无行情'], 'json');
        }
        // 查询价格
        $data      = $data[$code];
        $now_price = $data[3];
        $status    = 0;
        if ($now_price > $price) {
            // todo:是否进入委托交易
            $status = 1;
        }
        // 检查持仓记录
        $dbposition = M('StockPosition');
        $logid      = $dbposition->where([
            'muid'  => $this->_userinfo['muid'],
            'code'  => $code,
            'ctime' => 0
        ])->getField('sid');
        $dbmember   = M('Member');
        // 无论是委托交易还是 事实交易 都先减去可用金额
        $dbmember->where(['muid' => $this->_userinfo['muid']])->setDec('bankroll', ($price * $amount));
        if (empty($logid)) {
            $logid = md5($this->_userinfo['muid'] . '_' . $code . '_' . time());
            $dbposition->data([
                'sid'   => $logid,
                'muid'  => $this->_userinfo['muid'],
                'code'  => $code,
		'price' => $price,
                'total' => ($status ? 0 : $amount),
                'atime' => ($status ? 0 : time())
            ])->add();
        } else {
            if ($status == 0) {
                $dbposition->where(['sid' => $logid])->setInc('total', $amount);
            }
        }
        // 创建交易流水
        $slogid  = md5($this->_userinfo['muid'] . '_' . $code . '_0_' . time());
        $loddata = [
            'type'    => 0,
            'id'      => $slogid,
            'spid'    => $logid,
            'code'    => $code,
            'status'  => $status,
            'total'   => $amount,
            'price'   => $price,
            'present' => $now_price,
            'addtime' => time(),
            'trtime'  => ($status ? 0 : time()),
            'muid'    => $this->_userinfo['muid']
        ];
        $dblog   = M('StockTradesLog');
        $ref     = $dblog->data($loddata)->add();
        if ($ref) {
	    // 更新均价
            if($status==0) {
                $avacost = $dblog->field(['sum(price*total)/sum(total) as avaCost'])->where([
                    'spid' => $logid,
                    'type' => 0,
                    'trtime'=>['GT',0]
                ])->find();
                $dbposition->data(['price' => $avacost['avaCost']])->where(['sid' => $logid])->save();
            }
            $this->response(['code' => 0, 'msg' => ($status ? '购买成功进入委托流程' : '交易成功')], 'json');
        } else {
            // todo: 加入回滚机制
            $this->response(['code' => __LINE__, 'msg' => '操作失败'], 'json');
        }
    }

    /**
     * 卖出
     */
    public function offtake()
    {
        if(parent::checktime()==false){
            $this->response(['code'=>__LINE__,'msg'=>'交易时间已经结束']);
        }
        // 买入后 进入到自选队列
        $amount = I('post.amount', 0, 'int');
        if (empty($amount)) {
            $this->response(['code' => __LINE__, 'msg' => '请输入购买数量'], 'json');
        }
        $code = I('post.stockCode', 0, 'int');
        if (empty($code)) {
            $this->response(['code' => __LINE__, 'msg' => '请输入正确的股票代码'], 'json');
        }
        $db_stock   = M('Stock');
        $stock_type = $db_stock->where(['code' => $code])->getField(['type']);
        if (in_array($stock_type, [0, 1, 2])) {
            $now_code = 'sh' . $code;
        } elseif (in_array($stock_type, [3, 4, 5,16,15])) {
            $now_code = 'sz' . $code;
        } else {
            $this->response(['code' => __LINE__, 'msg' => '请输入正确的股票代码'], 'json');
        }
        // 卖出价格
        $price = I('post.price', 0);
        if (empty($price) || !is_numeric($price)) {
            $this->response(['code' => __LINE__, 'msg' => '股票价格不正确'], 'json');
        }
        // 检查可卖出的股票 持仓股票-减去当日购买的股票量
        // 检查持仓记录
        $dbposition = M('StockPosition');
        $position   = $dbposition->field(['sid', 'total','price'])->where([
            'muid'  => $this->_userinfo['muid'],
            'code'  => $code,
            'ctime' => 0
        ])->find();
        if (empty($position['total'])) {
            $this->response(['code' => __LINE__, 'msg' => '当前股票超出可收买的数量'], 'json');
        }
        // 查看当日购买量
        $dblog      = M('StockTradesLog');
        $logs_total = $dblog->where([
            'spid'   => $position['sid'],
            'type'   => 0,
            'trtime' => array(
                'between',
                array(strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59')))
            )
        ])->sum('total');
        $ktotal     = $position['total'] - $logs_total;
        if ($ktotal < $amount) {
            $this->response(['code' => __LINE__, 'msg' => '当前股票超出可售卖的数量'], 'json');
        }
        // 查询实时行情
        import('Common.Util.Stock');
        $stock = new \Stock();
        $data  = $stock->GetQuote($now_code);
        if (empty($data)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无行情'], 'json');
        }
        $data = $data[$code];
        // 股票现价
        $now_price = $data[3];
        $status    = 0;
        if ($price > $now_price) {
            //$this->response(['code' => __LINE__, 'msg' => '暂不支持委托交易'], 'json');
            $status = 1;
        }
        // 减去持仓
        $dbposition->where(['sid' => $position['sid']])->setDec('total', $amount);
        // 完成交易加入可用资金
        if ($status == 0) {
            $dbmember = M('Member');
            $dbmember->where(['muid' => $this->_userinfo['muid']])->setInc('bankroll', ($price * $amount));
        }
        // 创建交易流水
        $slogid  = md5($this->_userinfo['muid'] . '_' . $code . '_1_' . time());
        $loddata = [
            'type'    => 1,
            'id'      => $slogid,
            'spid'    => $position['sid'],
            'code'    => $code,
            'status'  => $status,
            'total'   => $amount,
            'price'   => $price,
            'present' => $position['price'],
            'addtime' => time(),
            'trtime'  => ($status ?0:time()),
            'muid'    => $this->_userinfo['muid']
        ];
        $dblog   = M('StockTradesLog');
        if(empty($position['price'])){
		$avacost = $dblog->field(['sum(price*total)/sum(total) as avaCost'])->where(['spid'=>$position['sid'],'type'=>0,'trtime'=>['GT',0]])->find();
        	$loddata['present']=$avacost['avaCost'];
	}
        $ref     = $dblog->data($loddata)->add();
        if ($ref) {
            $this->response(['code' => 0, 'msg' => ($status ? '卖出成功进入委托流程' : '交易成功')], 'json');
        } else {
            // todo: 加入回滚机制
            $this->response(['code' => __LINE__, 'msg' => '操作失败'], 'json');
        }
    }

    /**
     * 自选股票同步
     */
    public function sync()
    {
        $code = I('code');
        if (empty($code)) {
            $this->response(['code' => __LINE__, 'msg' => '请传入股票id'], 'json');
        }
        $dbcode = M('Stock');
        $count  = $dbcode->where(['code' => ['EQ', $code]])->count();
        if (empty($count)) {
            $this->response(['code' => __LINE__, 'msg' => '股票不存在'], 'json');
        }
        $dboptional = M('optional');
        $id         = md5($code . '_' . $this->_userinfo['muid']);
        $count      = $dboptional->where(['id' => ['EQ', $id]])->count();
        if (empty($count)) {
            // 关注
            $req = $dboptional->data([
                'id'    => $id,
                'code'  => $code,
                'uid'   => $this->_userinfo['muid'],
                'itime' => time()
            ])->add();
            if (empty($req)) {
                $this->response(['code' => __LINE__, 'msg' => '关注失败'], 'json');
            } else {
                $this->response(['code' => 0, 'msg' => '关注成功', 'data' => 1], 'json');
            }
        } else {
            // 取消
            $dboptional->where(['id' => ['EQ', $id]])->delete();
            $this->response(['code' => 0, 'msg' => '取消成功', 'data' => 0], 'json');
        }
    }

    /**
     * 发布观点
     */
    public function point()
    {
        $title = I('post.title', '', 'trim');
        $msg   = I('post.contentMsg', '', 'trim');
        if (empty($title) || empty($msg)) {
            $this->response(['code' => __LINE__, 'msg' => '观点名称标题不可为空'], 'json');
        }
        $db  = M('Point');
        $ref = $db->data([
            'title'  => $title,
            'msg'    => $msg,
            'muid'   => $this->_userinfo['muid'],
            'atime'  => time(),
            'addrip' => get_client_ip()
        ])->add();
        if (empty($ref)) {
            $this->response(['code' => __LINE__, 'msg' => '发布失败'], 'json');
        }
        $this->response(['code' => 0, 'msg' => '发布成功请耐心等待审核'], 'json');
    }

    /**
     * test
     * 发布视频
     */
    public function video()
    {
        $title = I('post.title', '', 'trim');
        $msg   = I('post.contentMsg', '', 'trim');
        if (empty($title) || empty($msg)) {
            $this->response(['code' => __LINE__, 'msg' => '观点名称标题不可为空'], 'json');
        }
        $upload           = new \Think\Upload();
        $upload->exts     = array('mp4', 'mpeg', 'avi', 'vob');
        $upload->hash     = true;
        $upload->rootPath = WEB_ROOT;
        $upload->savePath = 'Uploads' . DIRECTORY_SEPARATOR . 'video' . DIRECTORY_SEPARATOR . 'nb' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
        $upload->replace  = false;
        $upload->autoSub  = true;
        $info             = $upload->upload();
        if (empty($info)) {
            $this->response(['code' => __LINE__, 'msg' => $upload->getError()], 'json');
        }
        $info = array_pop($info);
        $file = $info['savepath'] . $info['savename'];
        $db   = M('Video');
        $ref  = $db->data([
            'title'  => $title,
            'msg'    => $msg,
            'muid'   => $this->_userinfo['muid'],
            'atime'  => time(),
            'type'   => 1,
            'video'  => $file,
            'addrip' => get_client_ip()
        ])->add();
        if (empty($ref)) {
            $this->response(['code' => __LINE__, 'msg' => '发布失败'], 'json');
        }
        $this->response(['code' => 0, 'msg' => '发布成功请耐心等待审核'], 'json');
    }

    /**
     * 视频点赞处理 每个用户只能出发一次
     * 1 点赞 2 倒彩
     */
    public function vsub()
    {
        $mid    = I('post.mid', 0, 'intval');
        $method = I('post.operation', 0, 'intval');
        if (empty($mid) || !in_array($method, [1, 2])) {
            $this->response(['code' => __LINE__, 'msg' => '无效参数'], 'json');
        }
        $sid     = md5($mid . '_' . $this->_userinfo['muid']);
        $dbVideo = M('Video');
        $rep     = $dbVideo->field('id')->where(['id' => $mid, 'status' => 1])->find();
        if (empty($rep)) {
            $this->response(['code' => __LINE__, 'msg' => '视频不存在'], 'json');
        }
        $dbvr = M('VideoRecommend');
        $rep  = $dbvr->field('rid')->where(['rid' => $sid])->find();
        if (!empty($rep)) {
            $this->response(['code' => __LINE__, 'msg' => '已经操作过'], 'json');
        }
        $rep = $dbvr->data([
            'rid'    => $sid,
            'rtype'  => $method,
            'mid'    => $mid,
            'muid'   => $this->_userinfo['muid'],
            'rtime'  => time(),
            'addrip' => get_client_ip()
        ])->add();

        if (empty($rep)) {
            $this->response(['code' => __LINE__, 'msg' => '操作失败'], 'json');
        } else {
            if ($method == 1) {
                $dbVideo->where(['id' => $mid])->setInc('recommend_add', 1);
            } else {
                $dbVideo->where(['id' => $mid])->setInc('recommend_sub', 1);
            }
            $this->response(['code' => 0, 'msg' => '操作成功'], 'json');
        }
    }

    /**
     * 视频列表
     */
    function vlist()
    {
        // 视频列表
        $type      = I('post.type', 0, 'intval');
        $showCount = I('post.showCount', 15, 'intval');
        $pageCount = I('post.pageCount', 1, 'intval');
        $pageCount = max($pageCount, 1);
        if (!in_array($type, [1, 2])) {
            $this->response(['code' => __LINE__, 'msg' => '类型不正确'], 'json');
        }
        $dbVideo = M('Video');
        $total   = $dbVideo->where(['type' => $type, 'status' => 1])->count();
        if (empty($total)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无数据'], 'json');
        }
        $lists = $dbVideo->field([
            'id as videoId',
            'title as videoTitle',
            'video as videoImg',
            'atime as videoTime',
            'recommend_sub as videoBad',
            'recommend_add as  videoGood',
            'repcount as videoMsg',
            'author as videoAuthor'
        ])->where(['type' => $type, 'status' => 1])->order(array(
            'atime' => 'desc'
        ))->limit((($pageCount - 1) * $showCount) . ',' . $showCount)->select();
        if (empty($lists)) {
            $this->response(['code' => __LINE__, 'msg' => '最后一页'], 'json');
        }
        foreach ($lists as $k => $list) {
            $list['videoImg']  = U(substr($list['videoImg'], 0, -4) . '_thumb.jpg', '', '', true);
            $list['videoLink'] = U('Home/video/show', ['id' => $list['videoId']], 'html', true);
            $lists[$k]         = $list;
        }
        $this->response(['code' => 0, 'data' => ['list' => $lists, 'totalCount' => $total]], 'json');
    }

    /**
     * 观看日志
     */
    public function vlog()
    {
        $type      = I('post.type', 1, 'intval');
        $showCount = I('post.showCount', 15, 'intval');
        $pageCount = I('post.pageCount', 1, 'intval');
        $pageCount = max($pageCount, 1);
        $ttime     = I('post.time', 1, 'intval');
        if (!in_array($ttime, [1, 2, 3]) || !in_array($type, [1, 2])) {
            $this->response(['code' => __LINE__, 'msg' => '参数错误'], 'json');
        }
        if ($type == 2) {
            $showdate = date('Y-m-d', (time() - 86400));
        } elseif ($type == 3) {
            $showdate = date('Y-m-d', (time() - 172800));
        } else {
            $showdate = date('Y-m-d');
        }
        $dbwlog = M('VideoWatchLog');
        $ref    = $dbwlog->where(['wdate' => $showdate, 'mid' => $this->_userinfo['muid']])->count();
        if (empty($ref)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无观看记录'], 'json');
        }
        // 获取所有的记录
        $ref  = $dbwlog->field(['vid', 'showtime', 'wtime'])->where([
            'wdate' => $showdate,
            'mid'   => $this->_userinfo['muid']
        ])->limit((($pageCount - 1) * $showCount) . ',' . $showCount)->select();
        $logs = [];
        foreach ($ref as $k => $v) {
            $logs[$v['vid']] = $v;
        }
        // 读取视频库
        $dbVideo = M('Video');
        $total   = $dbVideo->where(['type' => $type, 'id' => ['in', array_keys($logs)]])->count();
        if (empty($total)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无观看记录'], 'json');
        }
        $data = $dbVideo->field('id as videoId,title as videoTitle')->where([
            'type' => $type,
            'id'   => ['in', array_keys($logs)]
        ])->select();

        foreach ($data as $k => $v) {
            $v['videoLink'] = U('Home/video/show', ['id' => $v['videoId']], 'html', true);
            $v['watchTime'] = $logs[$v['videoId']]['showtime'];
            $v['watchDate'] = date('H:i', $logs[$v['videoId']]['wtime']);
            $data[$k]       = $v;
        }
        $this->response(['code' => 0, 'data' => ['list' => $data, 'totalCount' => $total]], 'json');
    }
}
